<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Check } from '@element-plus/icons-vue';
import { SecondHandItemApi } from '@/api/SecondHandItemApi.js';
import { AddressApi } from '@/api/new/userAddrApi.ts';
import { MarketItemApi } from '@/api/new/MarketItemApi.ts';
import UserUtil from '@/utils/User/User.js';
import { TransactionOrderApi } from '@/api/TransactionOrderApi.js';

const route = useRoute();
const router = useRouter();
const itemID = computed(() => Number(route.params.id));

// 商品信息
const product = ref({});
const productImage = ref('');
const loading = ref(true);
const submitting = ref(false);

// 地址相关
const addressList = ref([]);
const selectedAddress = ref(null);
const showAddressDialog = ref(false);
const showAddAddressForm = ref(false);
const savingAddress = ref(false);

// 订单备注
const remark = ref('');

// 默认图片
const defaultImage = 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png';

// 地址表单
const addressForm = reactive({
  addrID: null,
  userID: null,
  address: '',
  phone: '',
  status: false
});

// 获取商品详情
const fetchProductDetail = async () => {
  loading.value = true;
  try {
    // 获取商品基本信息
    const response = await SecondHandItemApi.getSecondHandItemById(itemID.value);
    product.value = response.data || {};

    // 获取商品图片
    const imagesResponse = await MarketItemApi.getItemImages(itemID.value);
    if (imagesResponse && Array.isArray(imagesResponse) && imagesResponse.length > 0) {
      productImage.value = imagesResponse[0].imageUrl;
    } else if (imagesResponse && imagesResponse.imageUrl) {
      productImage.value = imagesResponse.imageUrl;
    }
  } catch (error) {
    ElMessage.error(`获取商品详情失败: ${error.message}`);
  } finally {
    loading.value = false;
  }
};

// 获取用户地址列表
const fetchAddressList = async () => {
  try {
    const userInfo = await UserUtil.getUserInfo();
    if (!userInfo || !userInfo.userID) {
      ElMessage.warning('请先登录');
      return;
    }

    const response = await AddressApi.getAddressList(userInfo.userID);
    addressList.value = response || [];

    // 如果有默认地址，则选中默认地址
    const defaultAddr = addressList.value.find(addr => addr.status);
    if (defaultAddr) {
      selectedAddress.value = defaultAddr.addrID;
    } else if (addressList.value.length > 0) {
      // 否则选中第一个地址
      selectedAddress.value = addressList.value[0].addrID;
    }
  } catch (error) {
    ElMessage.error(`获取地址列表失败: ${error.message}`);
  }
};

// 显示新增地址表单
const showNewAddressForm = async () => {
  // 重置表单
  addressForm.addrID = null;
  addressForm.address = '';
  addressForm.phone = '';
  addressForm.status = false;

  // 获取用户ID
  const userInfo = await UserUtil.getUserInfo();
  addressForm.userID = userInfo.userID;

  showAddAddressForm.value = true;
};

// 编辑地址
const editAddress = (addr) => {
  addressForm.addrID = addr.addrID;
  addressForm.userID = addr.userID;
  addressForm.address = addr.address;
  addressForm.phone = addr.phone;
  addressForm.status = addr.status;

  showAddAddressForm.value = true;
};

// 删除地址
const deleteAddress = async (addrID) => {
  try {
    await ElMessageBox.confirm('确定要删除这个地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await AddressApi.deleteAddress(addrID);
    ElMessage.success('删除地址成功');

    // 刷新地址列表
    fetchAddressList();

    // 如果删除的是当前选中的地址，则重置选中状态
    if (selectedAddress.value === addrID) {
      selectedAddress.value = null;
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`删除地址失败: ${error.message}`);
    }
  }
};

// 保存地址
const saveAddress = async () => {
  // 表单验证
  if (!addressForm.address.trim()) {
    ElMessage.warning('请输入详细地址');
    return;
  }

  if (!addressForm.phone.trim()) {
    ElMessage.warning('请输入联系电话');
    return;
  }

  savingAddress.value = true;

  try {
    if (addressForm.addrID) {
      // 更新地址
      await AddressApi.updateAddress(addressForm);
      ElMessage.success('更新地址成功');
    } else {
      // 新增地址
      const response = await AddressApi.addAddress(addressForm);
      ElMessage.success('添加地址成功');

      // 如果是第一个地址，自动选中
      if (addressList.value.length === 0) {
        selectedAddress.value = response.addrID;
      }
    }

    // 刷新地址列表
    fetchAddressList();

    // 关闭表单
    showAddAddressForm.value = false;
  } catch (error) {
    ElMessage.error(`保存地址失败: ${error.message}`);
  } finally {
    savingAddress.value = false;
  }
};

// 提交订单
const submitOrder = async () => {
  // 验证是否选择了地址
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址');
    return;
  }

  // 验证商品状态
  if (!product.value || product.value.status !== 'forSale') {
    ElMessage.warning('该商品已不可购买');
    return;
  }

  submitting.value = true;

  try {
    const userInfo = await UserUtil.getUserInfo();
    if (!userInfo || !userInfo.userID) {
      ElMessage.warning('请先登录');
      return;
    }

    // 构建订单参数
    const orderParams = {
      itemID: itemID.value,
      buyerID: userInfo.userID,
      sellerID: product.value.sellerID,
      status: 'inProgress',
      createTime: new Date().toISOString(),
      addrID: selectedAddress.value
    };

    // 调用购买API
    const response = await MarketItemApi.purchaseItem(orderParams);

    ElMessage.success('订单提交成功');

    // 获取最新的订单
    try {
      const ordersResponse = await TransactionOrderApi.getTransactionOrdersByBuyerId(userInfo.userID);
      let orders = [];

      if (Array.isArray(ordersResponse)) {
        orders = ordersResponse;
      } else if (ordersResponse && Array.isArray(ordersResponse.data)) {
        orders = ordersResponse.data;
      }

      // 按创建时间排序，获取最新的订单
      if (orders.length > 0) {
        // 尝试将日期字符串转换为时间戳进行排序
        orders.sort((a, b) => {
          try {
            const timeA = new Date(a.creationTime).getTime();
            const timeB = new Date(b.creationTime).getTime();
            return timeB - timeA; // 降序排列，最新的在前面
          } catch (e) {
            return 0;
          }
        });

        // 获取最新的订单ID
        const latestOrderID = orders[0].orderID;

        // 跳转到订单列表
        await router.push('/user/order');
        return;
      }
    } catch (error) {
      console.error('获取最新订单失败:', error);
    }

    // 如果获取最新订单失败，则跳转到订单列表页面
    await router.push('/user/order');

  } catch (error) {
    ElMessage.error(`提交订单失败: ${error.message}`);
  } finally {
    submitting.value = false;
  }
};

// 页面加载时获取数据
onMounted(async () => {
  await fetchProductDetail();
  await fetchAddressList();
});
</script>

<template>
  <div class="confirm-order-container">
    <div class="order-title">确认订单</div>

    <!-- 收货地址 -->
    <div class="address-section">
      <div class="section-header">
        <div class="section-title">收货地址</div>
        <el-button type="text" @click="showAddressDialog = true">管理地址</el-button>
      </div>

      <div v-if="loading" class="loading-placeholder">
        <el-skeleton :rows="2" animated />
      </div>

      <div v-else-if="!addressList || addressList.length === 0" class="empty-address">
        <el-empty description="暂无收货地址" />
        <el-button type="primary" @click="showAddressDialog = true">添加地址</el-button>
      </div>

      <div v-else class="address-list">
        <div
          v-for="addr in addressList"
          :key="addr.addrID"
          class="address-item"
          :class="{ active: selectedAddress === addr.addrID }"
          @click="selectedAddress = addr.addrID"
        >
          <div class="address-content">
            <div class="address-info">{{ addr.address }}</div>
            <div class="contact-info">{{ addr.phone }}</div>
          </div>
          <div class="address-check" v-if="selectedAddress === addr.addrID">
            <el-icon><Check /></el-icon>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品信息 -->
    <div class="product-section">
      <div class="section-title">商品信息</div>

      <div v-if="loading" class="loading-placeholder">
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else class="product-card">
        <div class="product-image" :style="{ backgroundImage: `url(${productImage || defaultImage})` }"></div>
        <div class="product-info">
          <div class="product-title">{{ product.title }}</div>
          <div class="product-price">¥{{ product.price }}</div>
        </div>
      </div>
    </div>

    <!-- 订单备注 -->
    <div class="remark-section">
      <div class="section-title">订单备注</div>
      <el-input
        v-model="remark"
        type="textarea"
        :rows="2"
        placeholder="选填，请填写与卖家沟通的要求"
        maxlength="200"
        show-word-limit
      />
    </div>

    <!-- 订单金额 -->
    <div class="price-section">
      <div class="price-item">
        <span>商品金额</span>
        <span class="price">¥{{ product.price || 0 }}</span>
      </div>
      <div class="price-item">
        <span>运费</span>
        <span class="price">¥0</span>
      </div>
      <div class="price-total">
        <span>实付款</span>
        <span class="total-price">¥{{ product.price || 0 }}</span>
      </div>
    </div>

    <!-- 提交订单 -->
    <div class="submit-section">
      <el-button type="primary" class="submit-btn" @click="submitOrder" :loading="submitting">
        提交订单
      </el-button>
    </div>

    <!-- 地址管理对话框 -->
    <el-dialog
      v-model="showAddressDialog"
      title="地址管理"
      width="500px"
    >
      <div class="address-dialog-content">
        <div v-if="!addressList || addressList.length === 0" class="empty-address">
          <el-empty description="暂无收货地址" />
        </div>

        <div v-else class="address-list-dialog">
          <div
            v-for="addr in addressList"
            :key="addr.addrID"
            class="address-item-dialog"
          >
            <div class="address-content">
              <div class="address-info">{{ addr.address }}</div>
              <div class="contact-info">{{ addr.phone }}</div>
            </div>
            <div class="address-actions">
              <el-button type="text" @click="editAddress(addr)">编辑</el-button>
              <el-button type="text" @click="deleteAddress(addr.addrID)">删除</el-button>
            </div>
          </div>
        </div>

        <div class="add-address-btn" v-if="!showAddAddressForm">
          <el-button type="primary" @click="showNewAddressForm">添加新地址</el-button>
        </div>

        <div class="address-form" v-if="showAddAddressForm">
          <el-form :model="addressForm" label-width="80px">
            <el-form-item label="详细地址">
              <el-input v-model="addressForm.address" placeholder="请输入详细地址"></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="addressForm.phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="addressForm.status">设为默认地址</el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveAddress" :loading="savingAddress">保存</el-button>
              <el-button @click="showAddAddressForm = false">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.confirm-order-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);

  .order-title {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 24px;
    color: #333;
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .section-title {
    font-size: 18px;
    font-weight: 500;
    color: #333;
  }

  .address-section,
  .product-section,
  .remark-section,
  .price-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  }

  .loading-placeholder {
    padding: 16px 0;
  }

  .empty-address {
    text-align: center;
    padding: 24px 0;
  }

  .address-list {
    .address-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      border: 1px solid #eee;
      border-radius: 8px;
      margin-bottom: 12px;
      cursor: pointer;
      transition: all 0.3s;

      &.active {
        border-color: #ff2442;
        background-color: #fff9fa;
      }

      &:hover {
        border-color: #ff2442;
      }

      .address-content {
        flex: 1;

        .address-info {
          font-size: 16px;
          margin-bottom: 8px;
        }

        .contact-info {
          font-size: 14px;
          color: #666;
        }
      }

      .address-check {
        color: #ff2442;
      }
    }
  }

  .product-card {
    display: flex;
    align-items: center;

    .product-image {
      width: 100px;
      height: 100px;
      background-size: cover;
      background-position: center;
      border-radius: 8px;
      margin-right: 16px;
    }

    .product-info {
      flex: 1;

      .product-title {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 8px;
      }

      .product-price {
        font-size: 18px;
        color: #ff2442;
        font-weight: 600;
      }
    }
  }

  .price-section {
    .price-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12px;
      font-size: 14px;
      color: #666;

      .price {
        color: #333;
      }
    }

    .price-total {
      display: flex;
      justify-content: space-between;
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #eee;
      font-size: 16px;
      font-weight: 500;

      .total-price {
        color: #ff2442;
        font-size: 20px;
        font-weight: 600;
      }
    }
  }

  .submit-section {
    margin-top: 24px;
    text-align: center;

    .submit-btn {
      width: 100%;
      height: 48px;
      font-size: 16px;
      background-color: #ff2442;
      border-color: #ff2442;

      &:hover {
        background-color: #e0203a;
        border-color: #e0203a;
      }
    }
  }

  .address-dialog-content {
    .address-list-dialog {
      max-height: 300px;
      overflow-y: auto;

      .address-item-dialog {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        border-bottom: 1px solid #eee;

        &:last-child {
          border-bottom: none;
        }

        .address-content {
          flex: 1;

          .address-info {
            font-size: 14px;
            margin-bottom: 4px;
          }

          .contact-info {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }

    .add-address-btn {
      margin-top: 16px;
      text-align: center;
    }

    .address-form {
      margin-top: 16px;
    }
  }
}
</style>
